using AutoMapper;
using MediatR;
using SqlSugar;
using TaskProject.Application.Command.Plan;
using TaskProject.Domain.Plan;
using TaskProject.ErrorCode;
using TaskProject.Extension.Plan;
using TaskProject.InfrasIntructure.Implement;

namespace TaskProject.Application.Handler.Plan
{
    /// <summary>
    /// 查询生产计划处理器
    /// </summary>
    public class GetProductionPlanHandler : IRequestHandler<GetProductionPlanCommand, APIResult<List<ProductionPlanDTO>>>
    {
        private readonly DatabaseContext _db;
        private readonly IMapper _mapper;

        public GetProductionPlanHandler(DatabaseContext db, IMapper mapper)
        {
            _db = db;
            _mapper = mapper;
        }

        public async Task<APIResult<List<ProductionPlanDTO>>> Handle(GetProductionPlanCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<ProductionPlanDTO>>();

            try
            {
                // 构建查询条件
                var query = _db.sqlSugar.Queryable<ProductionPlanModel>()
                    .Where(p => !p.IsDel);

                // 添加查询条件
                if (!string.IsNullOrEmpty(request.PlanSubject))
                {
                    query = query.Where(p => p.PlanSubject.Contains(request.PlanSubject));
                }

                if (!string.IsNullOrEmpty(request.PlanOrderNumber))
                {
                    query = query.Where(p => p.PlanOrderNumber.Contains(request.PlanOrderNumber));
                }

                if (!string.IsNullOrEmpty(request.SalesOrderNumber))
                {
                    query = query.Where(p => p.SalesOrderNumber.Contains(request.SalesOrderNumber));
                }

                if (request.PlanStatus.HasValue)
                {
                    query = query.Where(p => p.PlanStatus == request.PlanStatus.Value);
                }

                if (request.Priority.HasValue)
                {
                    query = query.Where(p => p.Priority == request.Priority.Value);
                }

                if (request.StartDate.HasValue)
                {
                    query = query.Where(p => p.DocumentDate >= request.StartDate.Value);
                }

                if (request.EndDate.HasValue)
                {
                    query = query.Where(p => p.DocumentDate <= request.EndDate.Value);
                }

                // 排序和分页
                var totalCount = await query.CountAsync(cancellationToken);
                var plans = await query
                    .OrderByDescending(p => p.CreateDate)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 转换为DTO
                var planDtos = new List<ProductionPlanDTO>();
                foreach (var plan in plans)
                {
                    var planDto = _mapper.Map<ProductionPlanDTO>(plan);

                    // 查询生产物品
                    var items = await _db.sqlSugar.Queryable<ProductionPlanItemModel>()
                        .Where(i => i.PlanId == plan.PlanId)
                        .OrderBy(i => i.SortOrder)
                        .ToListAsync(cancellationToken);

                    planDto.ProductionItems = _mapper.Map<List<ProductionPlanItemDTO>>(items);

                    // 查询附件
                    var attachments = await _db.sqlSugar.Queryable<ProductionPlanAttachmentModel>()
                        .Where(a => a.PlanId == plan.PlanId)
                        .OrderByDescending(a => a.UploadDate)
                        .ToListAsync(cancellationToken);

                    planDto.Attachments = _mapper.Map<List<ProductionPlanAttachmentDTO>>(attachments);

                    planDtos.Add(planDto);
                }

                result.Code = APIEnum.Success;
                result.Msg = "查询成功";
                result.Data = planDtos;
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.Fail;
                result.Msg = $"查询失败：{ex.Message}";
            }

            return result;
        }
    }
} 